package com.example.springmvcdemo.controller;

import com.example.springmvcdemo.model.MessageInfo;
import com.example.springmvcdemo.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private MessageService messageService;

    // 存储留言信息
    private List<MessageInfo>  messageInfos=new ArrayList<>();
    @RequestMapping("/getList")
    public List<MessageInfo> getList() {
        return messageService.queryMessage();
    }

    @RequestMapping(value="/publish",produces = "application/json") // 将返回值由String转为json
    public String publish(@RequestBody MessageInfo messageInfo) {   // @RequestBody用于将json格式的数据转换为对象
        if(StringUtils.hasLength(messageInfo.getFrom()) // 当message对象三个字段都不为空时,添加
                && StringUtils.hasLength(messageInfo.getTo())
                && StringUtils.hasLength(messageInfo.getMessage())) {
//            messageInfos.add(messageInfo);
            messageService.insertMessage(messageInfo);
            return "{\"ok\":1}";
        }
        return "{\"ok\":0}";
    }
}
